package com.phoenix.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    public static final String ORDER_EXCHANGE = "order_exchange";
    public static final String ORDER_QUEUE = "order_queue";
    public static final String ORDER_ROUTINGKEY = "order_routingkey";

    //创建并持久化交换机
    @Bean
    public DirectExchange orderExchange() {
        return ExchangeBuilder.directExchange(ORDER_EXCHANGE).durable(true).build();
    }

    //创建并持久化队列
    @Bean
    public Queue orderQueue() {
        return QueueBuilder.durable(ORDER_QUEUE)
                .deadLetterExchange("dlx.exchange")  //死信交换机
                .build();
    }

    //绑定队列到交换机
    @Bean
    public Binding orderBinding() {
        return BindingBuilder.bind(orderQueue())
                .to(orderExchange())
                .with(ORDER_ROUTINGKEY);
    }

    //配置消息转换器
    @Bean
    public Jackson2JsonMessageConverter jackson2JsonMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    //配置RabbitmqTemplate
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter());
        rabbitTemplate.setMandatory(true);
        //确认回调配置
        rabbitTemplate.setConfirmCallback((correlationData,ack,cause) -> {
            if(ack){
                System.out.println("✅ 消息到达Exchange，ID：" + correlationData.getId());
            }else {
                System.out.println("❌ 消息投递失败，ID：" + correlationData.getId() + "，原因：" + cause);
            }
        });

        //退回回调配置
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            System.out.println("🚨 消息路由失败！交换机：" + returnedMessage.getExchange() +
                    "，路由键：" + returnedMessage.getRoutingKey() + "，消息：" +
                    new String(returnedMessage.getMessage().getBody()));
        });

        return rabbitTemplate;
    }
}
